/**
 * @author  weigao<weigao@iflytek.com>
 *
 * @version 1.0.0
 */
package com.iflytek.uoamp.agent.monitor.dump;

import com.iflytek.uoamp.agent.common.util.PerDataUtils;
import com.iflytek.uoamp.agent.core.sender.monitorsender.requestObj.MonitorItemConfig;
import com.iflytek.uoamp.agent.core.sender.monitorsender.requestObj.MonitorItemResult;
import com.iflytek.uoamp.agent.monitor.dump.obj.DumpTask;

import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class PSInfoCache {

	private static PSInfoCache instance = new PSInfoCache();
	private PSInfoCache(){
		
	}
	
	public static PSInfoCache getInstance(){
		return instance;
	} 
	
	public static class PSInfo {
		private String pid;
		private int curStatus;

		public PSInfo(String pid,int curStatus){
			this.pid = pid;
			this.curStatus = curStatus;
		}
		
		public String getPid() {
			return pid;
		}

		public void setPid(String pid) {
			this.pid = pid;
		}

		public int getCurStatus() {
			return curStatus;
		}

		public void setCurStatus(int curStatus) {
			this.curStatus = curStatus;
		}

	}

	// 用于存储监控项的状态及其pid；
	// key为 host-displayname
	private Map<String, PSInfo> psInfo = new ConcurrentHashMap<String, PSInfo>();
	
	/**
	 * 获取监控项的信息
	 * @param task
	 * @return
	 */
	public PSInfo getPSInfo(DumpTask task){
		return psInfo.get(task.getIp()+"-"+task.getDisplay_name());
	}
	
	/**
	 * 将监控项的监控信息存入内存中；
	 * @param result
	 * @param config
	 */
	public final void putPsInfo(MonitorItemResult result,MonitorItemConfig config) {
		//不包含pid，直接跳过下面的处理
		if(!result.getOutput().contains("pid=")){
			return;
		}
		
		String host = config.getHost();
		String service = config.getServerDesc();
		int status = Integer.parseInt(result.getReturnCode());
		Map<String, String> map = PerDataUtils.getInstance().getPerData(result.getOutput());
		if(map==null){
			return;
		}
		String pid = map.get("pid");
		if(StringUtils.isEmpty(pid)){
			return;
		}
		psInfo.put(host+"-"+service, new PSInfo(pid, status));
	}
}
